
package main

import(
    "context"
    "log"
    "github.com/qiniu/qmgo"
    // "go.mongodb.org/mongo-driver/bson"
)


type MgoHub struct {
	// Register requests from the clients.
	inserts chan *MsgInfo
}

func newMgoHub() *MgoHub {
	return &MgoHub{
		inserts: make(chan *MsgInfo),
	}
}


type MsgInfo struct {
    From  string `bson:"from"`
    Type  string `bson:"type"`
    Msg   string `bson:"msg"`
    To    string `bson:"to"`
}

// var (
// 	ctx = context.Background()
// 	cli,_ = qmgo.Open(ctx, &qmgo.Config{Uri:"mongodb://localhost:27017", Database: "test", Coll: "messages"})
// )


func (h *MgoHub) run() {
	for {
		select{
			case msgItem := <-h.inserts:
				ctx := context.Background()
				cli,_ := qmgo.Open(ctx, &qmgo.Config{Uri:"mongodb://localhost:27017", Database: "test", Coll: "messages"})
				_, err := cli.InsertOne(ctx, msgItem)
				if err != nil {
					log.Printf("%v",err)
				}
				errc := cli.Close(ctx)
				log.Printf("close result %v",errc)
		}
	}
}